package com.seat.row.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.style.AbsoluteSizeSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;

/**
 * @author yhl 2015-9-18下午4:17:34
 */
public class UIUtil {

    public final static float DESIGN_WIDTH = 750;
    public static void resetDensity(Activity activity){
        Point size = new Point();
        ((WindowManager)activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(size);
        activity.getResources().getDisplayMetrics().xdpi = size.x/DESIGN_WIDTH*72f;
    }

    public static int dp2px(Context context, int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                context.getResources().getDisplayMetrics());
    }

    public static int px2dip(Context paramContext, float paramFloat) {
        return (int) (0.5F + paramFloat
                / paramContext.getResources().getDisplayMetrics().density);
    }

    public static void setNavParams(Context context, View view, int MENU_WIDTH, int MENU_HEIGHT) {
        LinearLayout.LayoutParams hostParams = (LinearLayout.LayoutParams) view.getLayoutParams();
        hostParams.width = UIUtil.dp2px(context, MENU_WIDTH);
        hostParams.height = UIUtil.dp2px(context, MENU_HEIGHT);
        view.setLayoutParams(hostParams);
    }

    public static void setReParams(Context context, View view, int MENU_WIDTH, int MENU_HEIGHT) {
        RelativeLayout.LayoutParams hostParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
        hostParams.width = UIUtil.dp2px(context, MENU_WIDTH);
        hostParams.height = UIUtil.dp2px(context, MENU_HEIGHT);
        view.setLayoutParams(hostParams);
    }


    public static byte[] bmpToByteArray(final Bitmap localBitmap,
                                        final boolean needRecycle) {
        try {
            ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
            localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                    localByteArrayOutputStream);
            localBitmap.recycle();
            byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
            try {
                localByteArrayOutputStream.close();
                return arrayOfByte;
            } catch (Exception e) {
                return null;
            }
        } catch (Exception e) {
            ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
            localBitmap.compress(Bitmap.CompressFormat.JPEG, 70,
                    localByteArrayOutputStream);
            localBitmap.recycle();
            byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
            try {
                localByteArrayOutputStream.close();
                return arrayOfByte;
            } catch (Exception ex) {
                return null;
            }
        }
    }

    public static byte[] bytesFromPath(String path, Context context) {
        try {
            Log.e("TAG", "path = " + path);
            FileInputStream fis = new FileInputStream(path);// "/mnt/sdcard/atsmart/example.jpg");//
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[8 * 1024 * 1024];
            for (int readNum; (readNum = fis.read(buf)) != -1; ) {
                if (bos.toByteArray().length < 100000) {
                    bos.write(buf, 0, readNum);
                } else {
                    break;
                }
            }
            bos.write("\r\n\r\n".getBytes("ISO-8859-1"));
            fis.close();
            return bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获得某个图片资源的宽�?
     *
     * @param context
     * @param drawableId
     * @return
     */
    public static int[] getImageWidthHeight(Context context, int drawableId) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(context.getResources(), drawableId, opts);
        opts.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
                drawableId, opts);
        return new int[]{bitmap.getWidth(), bitmap.getHeight()};
    }

    public static int getScreenHeight(Context context) {
        DisplayMetrics metrics = new DisplayMetrics();
        metrics = context.getResources().getDisplayMetrics();
        return metrics.heightPixels;
    }

    public static int getScreenWidth(Context context) {
        DisplayMetrics metrics = new DisplayMetrics();
        metrics = context.getResources().getDisplayMetrics();
        return metrics.widthPixels;
    }

    public static void setHint(EditText edit, String hint) {
        SpannableString ss = new SpannableString(hint);
        // 设置hint文字大小
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(15, true);
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        edit.setHint(new SpannedString(ss));
    }

    public static void setHintMid(EditText edit, String hint) {
        SpannableString ss = new SpannableString(hint);
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(17, true);
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        edit.setHint(new SpannedString(ss));
    }

    /**
     * 设置iamgeview 显示宽高
     *
     * @param iv
     * @param photoWidth
     * @param oldwidth
     * @param oldheight
     */
    public static void setImageViewParams(Context context, ImageView iv,
                                          int photoWidth, int oldwidth, int oldheight, int newH) {
        LayoutParams lp = iv.getLayoutParams();
        lp.width = photoWidth;
        if (newH == -1) {
            lp.height = (oldheight * photoWidth) / oldwidth;
        } else {
            lp.height = newH;
        }
        iv.setLayoutParams(lp);
    }

    public static void setButtonParams(Button iv, int photoWidth, int oldwidth,
                                       int oldheight, int newH) {
        LayoutParams lp = iv.getLayoutParams();
        lp.width = photoWidth;
        if (newH == -1) {
            lp.height = (oldheight * photoWidth) / oldwidth;
        } else {
            lp.height = newH;
        }
        iv.setLayoutParams(lp);
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        ((MarginLayoutParams) params).setMargins(10, 10, 10, 10);
        listView.setLayoutParams(params);
    }

}
